! This program searches for the n'th prime... but not in the most efficient
! way...
!
program prime

use time

implicit none

integer                            :: n, i, j, nb_divisor_checks
integer(kind=clock_kind)           :: mytime
real                               :: square
integer, dimension(:), allocatable :: primelist
logical                            :: is_prime

n = 340000  

nb_divisor_checks = 0

allocate(primelist(n))

call wallclock_tic()

primelist(1) = 2
primelist(2) = 3
write(unit=*, fmt="(A, I0, A, I0)") "Prime ", 1, ": ", primelist(1)

do i = 3,n

  primelist(i) = primelist(i-1)

  do

    primelist(i) = primelist(i) + 2
    is_prime = .true.

!    if( modulo(primelist(i),10)==5) then
!        exit
!        is_prime = .false.
!    endif
    do j = 2,i-1
      if(primelist(j)**2 > primelist(i)) exit
!      nb_divisor_checks = nb_divisor_checks + 1
    
      if (modulo(primelist(i), primelist(j)) == 0) then
        is_prime = .false.
        exit
      end if

    end do

    if (is_prime) then

      exit

    end if

  end do

end do

mytime = wallclock_toc()
write(unit=*, fmt="(A, I0, A, I0)") &
  "FINAL RESULT: Prime ", n, ": ", primelist(n)
write(unit=*, fmt="(I0, A, I0, A, ES10.2, A)") &
  nb_divisor_checks, " checks in ", mytime, " msec. = ", &
  1000.0*nb_divisor_checks/mytime, " checks/sec."

deallocate(primelist)

end program prime
